import api from "../api/api";
import tip from "./tip";
import store from "@/store/index";
import sr from "sr-sdk-wxapp";
import programSetting from "@/utils/programSetting";
import util from "@/utils/util";
import commonSensors from "@/utils/commonSensors.js";
import {
  MERCHANT_INFO,
  CUSTOMER_INFO,
  SYSTEM_INFO,
  USER_SPECICAL_INFO,
  PAGE_TITLES,
  GLOBAL_CONFIG_JSON,
  CART_KEY
} from "@/utils/constant";

import commonMorefunLogs from "./commonMorefunLogs.js";

let isClick = false;

function preventDoubleClick(seconds) {
  if (isClick) {
    return true;
  } else {
    isClick = true;
    setTimeout(() => {
      isClick = false;
    }, seconds || 2000);
    return false;
  }
}

function getStoreConfigOnly() {
  return new Promise(async (resolve, reject) => {
    // 统一请求global config配置信息，把所有配置项的path以','拼接
    let path = Object.keys(GLOBAL_CONFIG_JSON).join(",");
    const json = await api.getStoreInfo({
      method: "GET",
      query: {
        config_client_id: "efcloud",
        config_path: path,
        config_scope: "Store",
        config_scope_id: getApp().globalData.merchantInfo.cloudMerchantStoreId ||
          uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
        merchant_id: getApp().globalData.merchantInfo.cloudMerchantId ||
          uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
      },
    });
    if (json.code === 1000) {
      let configData = json.data;
      // 接口返回的所有global config信息的key组成数组，用来匹配对应字段存储
      let configKeys = Object.keys(configData);
      configKeys.forEach(function(item, index) {
        // 如果是非子属性的正常global config或者父属性开关
        if (!GLOBAL_CONFIG_JSON[item].isSon) {
          // 如果是不包含子属性的普通单一global config
          if (!GLOBAL_CONFIG_JSON[item].isFather) {
            if (configData[item].code == 1000) {
              if (item == "store/store_design/global_image_scaling") {
                let proportion = configData[item].data.value;
                let proportionArr = proportion.split(":");
                let result = proportionArr[0] / proportionArr[1];
                uni.setStorageSync(GLOBAL_CONFIG_JSON[item].localKey, result);
                if (GLOBAL_CONFIG_JSON[item].vuexKey !== "default") {
                  store.commit(GLOBAL_CONFIG_JSON[item].vuexKey, result);
                }
              } else if (item == "order/common/audit_cancel_order") {
                getApp().globalData.cancelTime = configData[item].data.value;
              } else if (item == "store/tabs/available_tabs") {
                // tabbar 在这里初始化
                let tabInfo = configData[item].data.value;
                getTabInfo(tabInfo);
              } else {
                uni.setStorageSync(
                  GLOBAL_CONFIG_JSON[item].localKey,
                  configData[item].data.value
                );
                if (GLOBAL_CONFIG_JSON[item].vuexKey !== "default") {
                  store.commit(
                    GLOBAL_CONFIG_JSON[item].vuexKey,
                    configData[item].data.value
                  );
                }
              }
            }
          }
          // 如果是包含子属性的global config配置组，需根据父属性开关是否开启决定是否存储相关配置信息
          else {
            // 如果父属性未开启或者该属性返回状态不成功，则不存储相关配置信息
            if (
              !configData[item].data.value ||
              configData[item].code !== 1000
            ) {
              uni.setStorageSync(
                GLOBAL_CONFIG_JSON[item].localKey,
                configData[item].data.value
              );
            }
            // 如果父属性是开启状态，处理相关配置信息
            else {
              uni.setStorageSync(
                GLOBAL_CONFIG_JSON[item].localKey,
                configData[item].data.value
              );
              if (GLOBAL_CONFIG_JSON[item].vuexKey !== "default") {
                store.commit(
                  GLOBAL_CONFIG_JSON[item].vuexKey,
                  configData[item].data.value
                );
              }
              let childKeysArr = Object.keys(GLOBAL_CONFIG_JSON[item].childObj);
              childKeysArr.forEach(function(childItem, childIndex) {
                uni.setStorageSync(
                  GLOBAL_CONFIG_JSON[item].childObj[childItem].localKey,
                  configData[childItem].data.value
                );
                if (
                  GLOBAL_CONFIG_JSON[item].childObj[childItem].vuexKey !==
                  "default"
                ) {
                  store.commit(
                    GLOBAL_CONFIG_JSON[item].childObj[childItem].vuexKey,
                    configData[childItem].data.value
                  );
                }
              });
            }
          }
        }
        // 如果是需要依据父属性开关的子属性，则在父属性开启的情况在父属性里面处理
        else {}
      });
      if (
        getApp().globalData.initTrack == 0 &&
        getApp().globalData.siteId != null &&
        getApp().globalData.reportUrl != null
      ) {
        // matomo.initTracker(
        //   getApp().globalData.reportUrl,
        //   getApp().globalData.siteId, {
        //     PAGE_TITLES,
        //   }
        // );
        // matomo.tracker.trackPageView(PAGE_TITLES["app/launch"], "app/launch");
        // matomo.tracker.trackPageView(
        //   PAGE_TITLES[getApp().globalData.pageUrl],
        //   getApp().globalData.pageUrl
        // );
        getApp().globalData.initTrack = 1;
      }
      resolve();
    } else {
      reject();
    }
  });
}

const getTabInfo = async (_tabInfo) => {
  const tabInfo = _tabInfo || store.state.tabInfo;
  let result = [];
  try {
    const processSubscribeList = tabInfo.map((tab) => {
      return new Promise(async (tabResolve) => {
        const item = tab.value;
        if (item.subscribe_id) {
          // 最多多三个订阅
          item.activeSubcribeInfo = [];
          item.templateIdArr = [];
          const processSubscribeIdList = item.subscribe_id
            .split(",")
            .filter((_, _idx) => _idx < 3)
            .map((subscribeId) => {
              return new Promise(async (resolve) => {
                const activitySubscribeDetailRes =
                  await util.getActivitySubscribeDetail(
                    subscribeId,
                    "",
                    "targetActivity"
                  );
                if (activitySubscribeDetailRes.code == 1000) {
                  const activitySubscribeInfo = activitySubscribeDetailRes.data;
                  if (activitySubscribeInfo.state !== 0) {
                    const customerSubscribeInfoRes =
                      await util.getCustomerSubscribeInfo(
                        subscribeId,
                        "",
                        "",
                        "",
                        "targetActivity"
                      );
                    if (customerSubscribeInfoRes.code !== 1000) {
                      const exec = () => {
                        const info = {
                          activitySubscribeId: activitySubscribeInfo.activitySubscribeId,
                          templateId: activitySubscribeInfo.templateId,
                        };
                        item.templateIdArr.push(
                          activitySubscribeInfo.templateId
                        );
                        item.activeSubcribeInfo.push(info);
                      };
                      if (activitySubscribeInfo.type === "auto") {
                        const nowTime = new Date().getTime();
                        const planSendTime = new Date(
                          activitySubscribeInfo.planSendTime.replace(/-/g, "/")
                        ).getTime();
                        if (planSendTime > nowTime) {
                          exec();
                        }
                      } else {
                        exec();
                      }
                    }
                  }
                }
                resolve();
              });
            });
          await Promise.all(processSubscribeIdList);
        }
        tab.value = item;
        tabResolve(tab);
      });
    });
    result = await Promise.all(processSubscribeList);
  } catch (error) {
    result = tabInfo;
  }
  uni.setStorageSync("tabInfo", result);
  store.commit("setTabInfo", result);
  return result;
};

function getCurrentTime() {
  let keep = "";
  let date = new Date();
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  let d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  let h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  let f = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  keep = y + "" + m + "" + d + "" + h + "" + f + "" + s;
  return keep; // 20160614134947
}

/** 公用价格处理
 * @auth: TiAmo
 * @param  {[number]} value [需要处理的金额]
 * @param  {[number]} num [非整数保留的小数位]
 */
function moneyFormat(value, num) {
  num = num > 0 && num <= 20 ? num : 2;
  value = parseFloat((value + "").replace(/[^\d\.-]/g, "")).toFixed(num) + ""; //将金额转成比如 123.45的字符串
  var valueArr = value.split(".")[0].split("").reverse(); //将字符串的数变成数组
  const valueFloat = value.split(".")[1]; // 取到 小数点后的值
  let valueString = "";
  for (let i = 0; i < valueArr.length; i++) {
    valueString +=
      valueArr[i] + ((i + 1) % 3 == 0 && i + 1 != valueArr.length ? "," : ""); //循环 取数值并在每三位加个','
  }
  let money = valueString.split("").reverse().join("") + "." + valueFloat; //拼接上小数位
  if (money.indexOf(".00") !== -1) {
    money = money.substring(0, money.length - 3);
  }
  return money;
}

function priceRulesDeal(data, itemCode) {
  return new Promise(async (resolve, reject) => {
    let memberDetails =
      uni.getStorageSync("memberDetails") || getApp().globalData.memberDetails;
    let cgid = memberDetails.customerGroupId;
    let clid = memberDetails.memberLevelId;
    let isActive = memberDetails.isActive == "Active";
    let priceRulesJson = [];
    let priceRulesJson1 = [];
    let priceRulesJson2 = [];
    let json = {
      price: 0,
      rulesPrice: 0,
      hasRule: false,
      rulesArr: [],
      itemCode: itemCode,
    };
    let yrJson = [];
    data.forEach(function(item, index, array) {
      if (item.showPreTag == 1) {
        let now = new Date().getTime() / 1000;
        let start =
          new Date(item.preStrategyStartTime.replace(/-/g, "/")).getTime() /
          1000;
        let end =
          new Date(item.preStrategyEndTime.replace(/-/g, "/")).getTime() / 1000;
        if (now - start >= 0 && end - now > 0) {
          // yrJson.push(item)
          yrJson.push({
            groupIds: item.groupIds,
            groupVisible: item.groupVisible,
            memberLevels: item.memberLevels,
            // prePriceTag: item.prePriceTag,
            // preStrategyEndTime: item.prePriceTag,
            // preStrategyStartTime: item.prePriceTag,
            priceTag: item.prePriceTag,
            showPreTag: item.showPreTag,
            strategyEndTime: item.preStrategyEndTime,
            strategyId: item.strategyId,
            strategyPrice: item.strategyPrice,
            strategyStartTime: item.preStrategyStartTime,
          });
        }
      }
    });
    data.forEach(function(item, index, array) {
      let now = new Date().getTime() / 1000;
      let start =
        new Date(item.strategyStartTime.replace(/-/g, "/")).getTime() / 1000;
      let end =
        new Date(item.strategyEndTime.replace(/-/g, "/")).getTime() / 1000;
      if (now - start >= 0 && end - now > 0) {
        priceRulesJson.push(item);
      }
    });
    priceRulesJson.forEach(function(item, index, array) {
      if (!item.groupIds && !item.memberLevels) {
        if (json.price == 0 && json.rulesPrice == 0) {
          json.price = item.strategyPrice;
          json.rulesPrice = item.strategyPrice;
          json.hasRule = true;
        }
      } else {
        if (item.groupVisible == 1) {
          priceRulesJson1.push(item);
        } else {
          let checkGroup = !item.groupIds ||
            (!!item.groupIds && item.groupIds.indexOf(cgid) !== -1);
          let checkMemberLevel = !item.memberLevels ||
            (!!item.memberLevels &&
              isActive &&
              item.memberLevels.indexOf(clid) !== -1);
          if (checkGroup && checkMemberLevel) {
            priceRulesJson1.push(item);
          } else {
            priceRulesJson2.push(item);
          }
        }
      }
    });
    priceRulesJson2.forEach(function(item, index, array) {
      for (var i = 1; i < priceRulesJson2.length; i++) {
        let levelSplice =
          JSON.stringify(item.memberLevels) ==
          JSON.stringify(priceRulesJson2[i].memberLevels);
        let groupSplice =
          JSON.stringify(item.groupIds) ==
          JSON.stringify(priceRulesJson2[i].groupIds);
        if (index !== i && levelSplice && groupSplice) {
          priceRulesJson2.splice(i, 1);
        }
      }
    });
    if (priceRulesJson1.length > 0) {
      if (priceRulesJson2.length > 0) {
        if (priceRulesJson2[0].strategyId > priceRulesJson1[0].strategyId) {
          priceRulesJson2.push(priceRulesJson1[0]);
        } else {
          priceRulesJson2.unshift(priceRulesJson1[0]);
        }
      } else {
        priceRulesJson2.push(priceRulesJson1[0]);
      }
    }
    json.rulesArr = priceRulesJson2.concat(yrJson);
    resolve(json);
    // return json
  });
}

/** 公用分享
 * @auth: TiAmo
 * @param  {[string]} res [分享来源，自定义按钮还是右上角系统分享]
 * @param  {[string]} title [分享标题]
 * @param  {[string]} path [分享的页面路径]
 * @param  {[string]} imageUrl [分享图片]
 */
function commonShare(res, title, path, imageUrl) {
  // 设置默认分享地址和默认标题，标题和分享图片非必传 path必传
  let defaultTitle = uni.getStorageSync("storeName") || 'THE MACALLAN EBOUTIQUE麦卡伦';
  // sr.track('page_share_app_message', {
  //   "from_type": res.from,
  //   "share_title": title || 'THE MACALLAN EBOUTIQUE麦卡伦',
  //   "share_path": path,
  //   "share_image_url": imageUrl,
  //   "share_to": "friends",
  // })
  return {
    title: title || defaultTitle,
    path: path,
    imageUrl: imageUrl,
  };
}

function unique(arr) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i].frontCode == arr[j].frontCode) {
        //第一个等同于第二个，splice方法删除第二个
        arr.splice(j, 1);
        j--;
      }
    }
  }
  return arr;
}

function isEnableEvaluate() {
  return new Promise(async (resolve, reject) => {
    let customerInfo = uni.getStorageSync("customerInfo");
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    if (!customerInfo.jwt) {
      commonLoginNew();
    } else {
      const shopCartList = await api.isEnableEvaluate({
        header: {
          jwt: customerInfo.jwt,
        },
        query: {
          store_id: merchantInfo.cloudMerchantStoreId,
        },
      });
      if (shopCartList.code === 1000) {
        uni.setStorageSync("isEnableEvaluate", options.sourcecode);
      }
    }
  });
}

/** 获取商品评价信息
 * @auth: TiAmo
 * @param  {[Boolean]} goodsId [商品id]
 * @param  {[Boolean]} isSelection [是否精选]
 * @param  {[Boolean]} isReview, [是否有评价图片]
 * @param  {[Boolean]} isPdp [是否PDP页面]
 * @return {Promise<void>}
 */
function getPdpEvaluate(goodsId, isSelection, isReview, isPdp) {
  return new Promise(async (resolve, reject) => {
    let merchantInfo =
      uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
    const pdpEvaluateInfo = await api.pdpEvaluate({
      query: {
        isReviewImages: isReview,
        isSelection: isSelection,
        isPdp: isPdp,
        itemId: goodsId,
        pageNo: 1,
        pageSize: 5,
        merchantId: merchantInfo.cloudMerchantId,
        storeId: merchantInfo.cloudMerchantStoreId,
      },
    });
    if (pdpEvaluateInfo.code === 1000) {
      resolve(pdpEvaluateInfo);
    } else {
      reject(pdpEvaluateInfo);
    }
  });
}

/**
 * 获取唯一编码 做为用户的唯一标识uid。 需要永久保存在缓存中
 * dashboard统计搜索词
 */
function getbasicAutoNumber() {
  return new Promise(async (resolve, reject) => {
    const number = await api.basicAutoNumber({
      method: "GET",
    });
    if (number.code === 1000) {
      let uid_number = number.data.number;
      uni.setStorageSync("searchUid", uid_number);
      resolve(number);
    } else {
      reject(number);
    }
  });
}

function reapplyJWT() {
  return new Promise(async (resolve, reject) => {
    let tokenCustomer = uni.getStorageSync(CUSTOMER_INFO);
    let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
    let openId = userSpecialInfo.openid;
    let lastLoginTime = uni.getStorageSync("lastLoginTime");
    if (!lastLoginTime) {
      uni.setStorageSync("lastLoginTime", new Date().getTime());
      let res = await uni.login();
      if (!res[1]) {
        reject();
      }
      if (res[1].code) {
        let systemInfo = uni.getSystemInfoSync();
        uni.setStorageSync(SYSTEM_INFO, systemInfo);
        const rlt = await api.obtainUserOpenid({
          query: {
            app_id: uni.getAccountInfoSync().miniProgram.appId,
            js_code: res[1].code,
          },
        });
        if (rlt.code === 1000) {
          if (rlt.data.openid) {
            uni.setStorageSync(USER_SPECICAL_INFO, rlt.data);
            //获取商户信息
            let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
            if (merchantInfo.cloudMerchantId) {
              let customerInfo = await api.checkUser({
                method: "POST",
                query: {
                  appId: uni.getAccountInfoSync().miniProgram.appId,
                  merchantId: getApp().globalData.merchantInfo.cloudMerchantId ||
                    uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
                  openId: rlt.data.openid,
                },
              });
              if (customerInfo.code == 1000) {
                getApp().globalData.userLogin = true;
                getApp().globalData.customerInfo = customerInfo.data;
                uni.setStorageSync(CUSTOMER_INFO, customerInfo.data);
              } else {
                getApp().globalData.userLogin = false;
              }
            }
          }
        }
      } else {
        reject(res);
      }
    } else {
      let nowLoginTime = new Date().getTime();
      if (lastLoginTime - nowLoginTime > 60000) {
        let res = await uni.login();
        if (!res[1]) {
          reject();
        }
        if (res[1].code) {
          let systemInfo = uni.getSystemInfoSync();
          uni.setStorageSync(SYSTEM_INFO, systemInfo);
          const rlt = await api.obtainUserOpenid({
            query: {
              app_id: uni.getAccountInfoSync().miniProgram.appId,
              js_code: res[1].code,
            },
          });
          if (rlt.code === 1000) {
            if (rlt.data.openid) {
              uni.setStorageSync(USER_SPECICAL_INFO, rlt.data);
              //获取商户信息
              let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
              if (merchantInfo.cloudMerchantId) {
                let customerInfo = await api.checkUser({
                  method: "POST",
                  query: {
                    appId: uni.getAccountInfoSync().miniProgram.appId,
                    merchantId: getApp().globalData.merchantInfo.cloudMerchantId ||
                      uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
                    openId: rlt.data.openid,
                  },
                });
                if (customerInfo.code == 1000) {
                  getApp().globalData.userLogin = true;
                  getApp().globalData.customerInfo = customerInfo.data;
                  uni.setStorageSync(CUSTOMER_INFO, customerInfo.data);
                } else {
                  getApp().globalData.userLogin = false;
                }
              }
            }
          }
        } else {
          reject(res);
        }
      } else {
        reject();
      }
    }
  });
}

function commonUniLogin() {
  return new Promise(async (resolve, reject) => {
    let res = await uni.login();
    if (res.length > 1 && res[1].code) {
      const rlt = await api.obtainUserOpenid({
        query: {
          app_id: uni.getAccountInfoSync().miniProgram.appId,
          js_code: res[1].code,
        },
      });
      if (rlt.code === 1000) {
        getApp().cl_tracker.push({
          identityType: "applet-wechat",
          identityValue: rlt.data.openid, // identityValue 是用户的open_id
          identityType2: "wechat-unionid",
          identityValue2: rlt.data.unionId || "",
        });
        uni.setStorageSync(USER_SPECICAL_INFO, rlt.data);
        uni.setStorageSync("uniLoginInfo", rlt.data);
				// 莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					openid: rlt.data.openid || "",
					unionId: rlt.data.unionId || "",
					msg: "commonUniLogin-api.obtainUserOpenid-请求成功",
				})
        resolve(rlt);
      } else {
				// 莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					data: JSON.stringify(rlt),
					msg: "commonUniLogin-api.obtainUserOpenid-请求失败",
				})
        reject(rlt);
      }
    } else {
			// 莫凡日志
			commonMorefunLogs.aliYunMorefunLogs({
				data: JSON.stringify(res),
				msg: "commonUniLogin-uni.login-code为空",
			})
      reject();
    }
  });
}

function commonLoginNew() {
  return new Promise(async (resolve, reject) => {
    let merchantInfo =
      uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
    // 如果取不到商户信息,就重新接口获取
    if (!merchantInfo || Object.keys(merchantInfo).length == 0) {
      const accountInfo = uni.getAccountInfoSync();
      let merchantInfoJson = await api.merchantInfo(
        accountInfo.miniProgram.appId
      );
      if (merchantInfoJson.code === 200) {
        merchantInfo = merchantInfoJson.data;
        uni.setStorageSync("merchantInfo", merchantInfoJson.data);
      }
    }
    let uniLoginInfo = uni.getStorageSync(USER_SPECICAL_INFO);
    //获取商户信息
    let customerInfo = await api.checkUser({
      method: "POST",
      query: {
        appId: uni.getAccountInfoSync().miniProgram.appId,
        merchantId: merchantInfo.cloudMerchantId,
        openId: uniLoginInfo.openid,
        unionId: uniLoginInfo.unionId || "",
        loginToken: uniLoginInfo.loginToken || "",
      },
    });
    if (customerInfo.code == 1000) {
      getApp().cl_tracker.push({
        identityType: "applet-wechat",
        identityValue: customerInfo.data.openId, // identityValue 是用户的open_id
        identityType2: "wechat-unionid",
        identityValue2: customerInfo.data.unionId,
      });
      uni.setStorageSync(CUSTOMER_INFO, customerInfo.data);
      getApp().globalData.customerInfo = customerInfo.data;
			srSetUser(customerInfo.data.openId, customerInfo.data.unionId);
      resolve(customerInfo);
    } else {
      uni.setStorageSync("sensorsIsMember", false);
      uni.setStorageSync("registrationStatus", false);
      getApp().globalData.hasRegister = false;
      commonSensors.noMember()
      reject(customerInfo);
    }
  });
}
//	有数埋点设置 用户openid
function srSetUser(openId,unionId){
	try{
		if(this.$sr){
		this.$sr.setUser({
				open_id: openId,
				union_id: unionId,
			})
		}
	}catch(e){}
}

function checkCartNew(from) {
  return new Promise(async (resolve, reject) => {
    let cart_key = "";
    let merchantInfo =
      uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
    let customerInfo =
      uni.getStorageSync("customerInfo") || getApp().globalData.customerInfo;
    if (customerInfo) {
      let res = await api.checkCart({
        method: "POST",
        header: {
          jwt: customerInfo.jwt,
        },
        query: {
          customerId: customerInfo.customerId,
          merchantId: merchantInfo.cloudMerchantId,
          orderSource: "wxapp",
          storeId: merchantInfo.cloudMerchantStoreId,
        },
      });
      if (res.code === 1000) {
        cart_key = res.data;
        uni.setStorageSync("cartKey", cart_key);
        getApp().globalData.cartKey = cart_key;
      } else {
        let cartRes = await api.initCart({
          method: "POST",
          header: {
            jwt: customerInfo.jwt,
          },
          query: {
            customerId: customerInfo.customerId,
            merchantId: merchantInfo.cloudMerchantId,
            orderSource: "wxapp",
            storeId: merchantInfo.cloudMerchantStoreId,
          },
        });
        cart_key = cartRes.data.cartKey;
        uni.setStorageSync("cartKey", cart_key);
        getApp().globalData.cartKey = cart_key;
      }
      getCartList();
      resolve(cart_key);
    } else {
      commonLoginNew();
      reject();
    }
  });
}

function getCartList(realCartKey) {
  return new Promise(async (resolve, reject) => {
    let merchantInfo =
      uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
    let customerInfo =
      uni.getStorageSync("customerInfo") || getApp().globalData.customerInfo;
    let cartKey = !!realCartKey ? realCartKey : uni.getStorageSync("cartKey");
    if (!customerInfo || !customerInfo.jwt) {
      commonLoginNew();
      reject();
    } else if (!cartKey) {
      checkCartNew();
      reject();
    } else {
      const member = await illegalPhoneCheck();
      if(member){
        const shopCartList = await api.getCartList({
            header: {
              jwt: customerInfo.jwt,
            },
          },
          cartKey
        );
        if (shopCartList.code === 1000) {
          let shopCollect = shopCartList.data;
          let cartlistData = shopCollect.items;
          if (
            cartlistData !== null &&
            !!cartlistData &&
            cartlistData.length > 0
          ) {
            if (!programSetting.customTabbar) {
              uni.setTabBarBadge({
                index: 2,
                text: shopCollect.availableTotalQty.toString(),
              });
            }
            getApp().globalData.cartNum = shopCollect.availableTotalQty;
            store.commit("changeCartNum", shopCollect.availableTotalQty);
          } else {
            if (!programSetting.customTabbar) {
              uni.removeTabBarBadge({
                index: 2,
              });
            }
            store.commit("changeCartNum", 0);
          }
          resolve(shopCartList.data);
        } else {
          reject(shopCartList.data);
        }
      }else{
        reject();
      }
    }
  });
}

function getMemberDetailNew() {
  return new Promise(async (resolve, reject) => {
    let customerInfo =
      uni.getStorageSync(CUSTOMER_INFO) || getApp().customerInfo;
    const memberDetailsResult = await api.getMemberDetails({
      header: {
        jwt: customerInfo.jwt,
      },
    });
		
    if (memberDetailsResult.code == 1000 && memberDetailsResult.data) {
      const phoneNumberReg = /^1\d{10}$/;
      if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
				uni.setStorageSync("sensorsIsMember", false);
        // 非大陆手机号按照非会员对待,重新入会
        uni.removeStorageSync('memberDetails');
        reject(null);
      }else{
        getApp().memberDetails = memberDetailsResult.data;
				uni.setStorageSync("sensorsIsMember", true);
        uni.setStorageSync("memberDetails", memberDetailsResult.data);
        commonSensors.commonSetProfile('member', memberDetailsResult.data)
        resolve(memberDetailsResult);
      }
    } else {
			uni.setStorageSync("sensorsIsMember", false);
      reject(memberDetailsResult);
    }
  });
}

//  非法手机号校验
function illegalPhoneCheck() {
  return new Promise(async (resolve, reject) => {
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || getApp().customerInfo;
    const member = uni.getStorageSync('memberDetails');
    if(member && member.mobile){
      const phoneNumberReg = /^1\d{10}$/;
      if(!phoneNumberReg.test(member.mobile)){
        // 非大陆手机号按照非会员对待,重新入会
        uni.removeStorageSync('memberDetails');
        reject(false);
      }else{
        resolve(true);
      }
    }else{
      const memberDetailsResult = await api.getMemberDetails({
        header: {
          jwt: customerInfo.jwt,
        },
      });
      if (memberDetailsResult.code == 1000 && memberDetailsResult.data) {
        const phoneNumberReg = /^1\d{10}$/;
        if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
          // 非大陆手机号按照非会员对待,重新入会
          uni.removeStorageSync('memberDetails');
          reject(false);
        }else{
          getApp().memberDetails = memberDetailsResult.data;
          uni.setStorageSync("memberDetails", memberDetailsResult.data);
          resolve(true);
        }
      } else {
        reject(false);
      }
    }
  });
}
/**
 * 搜索商品 商品列表
 */
function doSearchGoods(
  class_id,
  category_name,
  currentPage,
  pageSize,
  afterPage,
  q = "",
  is_sort,
  color_filter,
  material_filter,
  size_filter,
  style_filter
) {
  return new Promise(async (resolve, reject) => {
    // let that = this;
    // that.shopGridList = true;
    // this.isIdentifier = true;
    // this.identifier = 'new-items-lp-' + class_id;
    // this.itemsFooter = 'new-items-footer-lp-' + class_id;
    let memberDetails = uni.getStorageSync("memberDetails");
    let merchantInfo = uni.getStorageSync("merchantInfo");
    let pageAfter = currentPage == 1 ? "" : decodeURIComponent(afterPage);

    // 获取商品列表
    const json = await api.getGoodsListNew({
      query: {
        q: q,
        class_id: class_id || "",
        page_no: currentPage || '',
        page_size: pageSize,
        store_id: merchantInfo.cloudMerchantStoreId,
        merchant_id: merchantInfo.cloudMerchantId,
        is_sort: is_sort || '',
        color_filter: color_filter || '',
        material_filter: material_filter || '',
        size_filter: size_filter || '',
        style_filter: style_filter || '',
        group_id: !!memberDetails ? memberDetails.customerGroupId : 0,
        member_level_id: !!memberDetails ? memberDetails.memberLevelId : 0,
        member_status: !!memberDetails ? memberDetails.isActive : "Inactive",
        after_page: pageAfter,
      },
    });
    if (json.code === 1000) {
      for (let i = 0; i < json.data.content.length; i++) {
        if (json.data.content[i].skuCodes !== undefined) {
          sr.track("expose_sku_component", {
            sku: {
              sku_id: json.data.content[i].skuCodes?.[0].toString(),
              sku_name: json.data.content[i].itemName, // 若商品无sku_name时，可传spu_name信息
            },
            spu: {
              spu_id: !!uni.getStorageSync('openOuterItemId') ? json.data.content[i].outerItemId : !!uni
                .getStorageSync("youshuOpencc") ?
                json.data.content[i].frontCode.toString() : json.data.content[i].itemCode.toString(),
              spu_name: !!uni.getStorageSync("youshuOpencc") ?
                json.data.content[i].itemName + json.data.content[i].valueName : json.data.content[i]
                .itemName, // 若商品无spu_name时，可传sku_name信息
            },
            sku_category: [{
              sku_cat_id: json.data.content[i].categoryId.toString(),
              sku_cat_name: "全部商品",
              sku_parent_cat_id: "null", // 若已是顶级类目，传"null"
            }, ],
            shipping_shop: {
              shipping_shop_id: merchantInfo.cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
              shipping_shop_name: "THE MACALLAN EBOUTIQUE麦卡伦", // 到家类型对接智慧零售入口必传
            },
            sale: {
              original_price: parseFloat(json.data.content[i].price), // 对接智慧零售入口必传
              current_price: parseFloat(json.data.content[i].price), // 对接智慧零售入口必传
            },
            primary_image_url: json.data.content[i].majorUrl,
            // more...
          });
        }
      }
      resolve(json);
    } else {
      reject(json);
    }
  });
}

function getGoodsListFilter(
  cateCode,
  color_filter,
  material_filter,
  size_filter,
  style_filter
) {
  return new Promise(async (resolve, reject) => {
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
    const json = await api.getGoodsListFilter({
      query: {
        class_id: cateCode || "",
        store_id: merchantInfo.cloudMerchantStoreId || store_id,
        merchant_id: merchantInfo.cloudMerchantId || merchant_id,
        color_filter: color_filter,
        material_filter: material_filter,
        size_filter: size_filter,
        style_filter: style_filter,
      },
    });
    if (json.code === 1000) {
      resolve(json);
    } else {
      reject(json);
    }
  });
}

// 初始化任务中心
function setInitTaskCenter() {
  return new Promise(async (resolve, reject) => {
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let memberDetails = uni.getStorageSync("memberDetails");

    const res = await api.setTaskInit({
      method: "POST",
      header: {
        jwt: customerInfo.jwt,
      },
      query: {
        memberId: memberDetails.memberId,
        memberLevelId: memberDetails.memberLevelId,
        mobile: customerInfo.mobile,
      },
    });
    if (res.code === 1000) {
      resolve(res);
    } else {
      resolve(res);
    }
  });
}

function getFourthLevelAddress(areaNo, areaType, areaCode) {
  return new Promise(async (resolve, reject) => {
    const that = this;
    const addressJson = await api.getAreasListNew({
      query: {
        area_no: areaNo || "1",
        area_type: areaType,
        parent_code: areaCode || "000000000",
        sort_type: "zh",
      },
    });
    if (addressJson.code === 1000) {
      resolve(addressJson);
    } else {
      reject(addressJson);
    }
  });
}

// 防止处理多次点击
function preventReClick(methods, info) {
  // methods是需要点击后需要执行的函数， info是点击需要传的参数
  let that = this;
  if (that.noClick) {
    // 第一次点击
    that.noClick = false;
    if (info && info !== "") {
      // info是执行函数需要传的参数
      methods(info);
    } else {
      methods();
    }
    setTimeout(() => {
      that.noClick = true;
    }, 2000);
  } else {
    // 这里是重复点击的判断
  }
}

function getOrderInfo(orderId) {
  return new Promise(async (resolve, reject) => {
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    const orderJson = await api.getOrderInfo({
        header: {
          jwt: customerInfo.jwt,
        },
      },
      orderId
    );
    if (orderJson.code === 1000) {
      resolve(orderJson.data);
    } else {
      reject(orderJson.data);
    }
  });
}

function getSqbToken(orderCode) {
  return new Promise(async (resolve, reject) => {
    let that = this;
    let subject = "微信小程序支付";
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    const getTokenJson = await api.getSqbToken({
      method: "POST",
      header: {
        jwt: customerInfo.jwt,
      },
      query: {
        outTradeNo: orderCode,
        subject: subject,
      },
    });
    if (getTokenJson.code === 1000) {
      resolve(getTokenJson);
    } else {
      reject(getTokenJson);
    }
  });
}

function sqbPay(orderCode) {
  return new Promise(async (resolve, reject) => {
    resolve();
  });
}

function timeStatus(item) {
  return new Promise(async (resolve, reject) => {
    let nowTime = new Date().getTime();
    let drawStartTime = item.activitySelection.activitySelectionStartTime;
    let drawEndTime = item.activitySelection.activitySelectionEndTime;
    let promulgateTime = item.activitySelection.promulgateTime;
    let buyEndTime = item.activitySelection.buyEndTime;
    let activityStopTime = item.activitySelection.activityStopTime;
    let showTime;
    let showText;
    if (nowTime < drawStartTime) {
      showTime = util.timeFormat(drawStartTime) + " 开始登记";
      showText = "未开放登记信息";
    } else if (nowTime > drawStartTime && nowTime < drawEndTime) {
      showTime = util.timeFormat(drawEndTime) + " 登记结束";
      showText = "开放登记信息";
    } else if (nowTime > drawEndTime && nowTime < promulgateTime) {
      showTime = util.timeFormat(promulgateTime) + " 公布结果";
      showText = "等待公布结果";
    } else if (nowTime > promulgateTime && nowTime < buyEndTime) {
      showTime = util.timeFormat(buyEndTime) + " 活动结束";
      showText = "结果已公布";
    } else if (nowTime > buyEndTime && nowTime < activityStopTime) {
      showTime = util.timeFormat(buyEndTime) + " 活动结束";
      showText = "活动已结束";
    } else {
      showTime = "";
      showText = "";
    }

    let obj = {
      dateStatus: showTime,
      joinStatus: showText,
    };
    resolve(obj);
  });
}

function payMoney(obj, that, objOrder, pageName = "") {
  return new Promise(async (resolve, reject) => {
    const accountInfo = uni.getAccountInfoSync();
    if (!obj.orderCode) {
      return false;
    }
    let currentOrderInfo = obj;
    let tsActivityLimitList = !!obj.addition.tsActivityLimitList ?
      currentOrderInfo.addition.tsActivityLimitList?.[0] :
      !!obj.addition.forwardPurchaseActivityList ?
      obj.addition.forwardPurchaseActivityList?.[0] :
      "";
    let clTrackPrams = {
      c_product_id: "",
      c_product_name: "",
      c_product_brand: "",
      c_product_price: "",
      c_product_year: "",
      c_product_series: "",
      c_product_scenarios: "",
      c_product_taste: "",
      c_product_alcoholconcentration: "",
      c_product_volume: "",
      c_order_id: currentOrderInfo.orderCode,
      c_quantity: currentOrderInfo.itemQty,
      "c_order_remark ": currentOrderInfo.buyerRemark,
      c_amount: currentOrderInfo.payment,
      c_payment_channel: "收钱吧",
      c_campaignID:
        !!tsActivityLimitList && !!tsActivityLimitList.tsActivityId ?
        tsActivityLimitList.tsActivityId :
        !!tsActivityLimitList.forwardPurchaseActivityId ?
        tsActivityLimitList.forwardPurchaseActivityId : "",
      c_campaignName:
        !!tsActivityLimitList && !!tsActivityLimitList.tsActivityName ?
        tsActivityLimitList.tsActivityName :
        !!tsActivityLimitList.forwardPurchaseActivityName ?
        tsActivityLimitList.forwardPurchaseActivityName : "",
    };

    if (!!objOrder) {
      clTrackPrams.c_order_type = objOrder.orderType;
      clTrackPrams.c_purchase_type = objOrder.purchaseType;
    }
    currentOrderInfo.items.forEach(function(item, index) {
      clTrackPrams.c_product_id += item.itemId + ";";
      clTrackPrams.c_product_name += item.itemName + ";";
      clTrackPrams.c_product_price += item.price + ";";
      clTrackPrams.c_product_volume = item.skuProperties[0].valueName || JSON.parse(item.skuProperties)[0]
        .valueName + ";";
    });
    //订单-立即支付埋点
    if (obj.status == "WAIT_BUYER_PAY") {
      getApp().commonClTrack("c_ebmp_order_paid", clTrackPrams);
    }
    //商城-订单-继续付款
    if (obj.status == "BUYER_PART_PAYMENT") {
      // clTrackPrams.c_payment_channel = '收钱吧';
      getApp().commonClTrack("c_ebmp_order_continue_to_pay", clTrackPrams);
    }
    //商城-订单-付款提醒点击
    if (!!pageName) {
      clTrackPrams.c_pageName = pageName;
      getApp().commonClTrack("c_ebmp_order_reminder_of_payment", clTrackPrams);
    }

    try {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO) || "";
      let subject = "微信小程序支付";
      that.$EFSTracking.trackingOrder(
        "ORDER_PAY",
        obj.orderId,
        obj.items,
        obj.payment,
        obj.postFee,
        obj.discountFee,
        obj.itemTotal
      );
      let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];
      if (currPage.route == "pages/order/list") {
        currPage.$vm.backSuccess = true;
      }
			//	有数埋点设置当前页面路径
			const _page = currPage.$page && currPage.$page.fullPage ? currPage.$page.fullPath : currPage.route;
			that.$sr.setContext({ page: _page });
      getSqbToken(obj.orderCode)
        .then((res) => {
          uni.setStorageSync("buyerPartPayment", true);
          getOrderInfo(obj.orderId)
            .then((orderJsonObj) => {
              that.$sr.track("custom_order", {
                order: {
                  order_id: orderJsonObj.orderCode.toString(),
                  order_time: new Date(
                    orderJsonObj.orderTime.replace(/-/g, "/")
                  ).getTime() || new Date(orderJsonObj.orderTime).getTime(),
                  order_status: "pay",
                },
                sub_orders: [{
                  sub_order_id: orderJsonObj.orderCode.toString(),
                  order_amt: parseFloat(orderJsonObj.itemTotal),
                  pay_amt: parseFloat(orderJsonObj.payment),
                }, ],
              });
            })
            .catch((err) => {
              // console.log("getOrderInfo err", err);
            });
          uni.navigateTo({
            url: `plugin://lite-pos-plugin/cashierV2?token=` +
              res.data.order_token +
              `&appid=wx158a61365a8c8fd6&openid=` +
              customerInfo.openId,
          });
          resolve(res);
        })
        .catch((err) => {
          // console.log("getSqbToken err", err);
        });
    } catch (error) {
      // console.log(error);
      reject();
    }
  });
}

function getServerTime(areaNo, areaType, areaCode) {
  return new Promise(async (resolve, reject) => {
    const that = this;
    const json = await api.getServerTime({
      method: "POST",
      query: {},
    });
    if (json.code === 1000) {
      let time = JSON.parse(json.data);
      resolve(time.server_date);
    }
  });
}
//判断订单类型是私卖订单、抽签购订单、常规订单
function isOrderType(currentOrder, orderFlow) {
  let addition = currentOrder.addition;
  let obj = {};
  if (!!addition && !!addition.hasPrivateSaleSku) {
    //私卖订单
    obj.orderType = "会员活动";
    if (addition?.tsActivityLimitList?.[0]?.selectionEnabled) {
      obj.purchaseType = "立即购买(抽签)";
    } else {
      obj.purchaseType = "立即购买";
    }
  } else if (
    !!addition &&
    !addition.hasActivityGroup &&
    !addition.activitySelectionId &&
    !addition.hasPrivateSaleSku &&
    !addition.takeForwardPurchase
  ) {
    obj.orderType = "常规购买"; //普通订单
    if (!!orderFlow) {
      //开启预约
      obj.purchaseType = "预约购买";
    } else {
      obj.purchaseType = "立即购买";
    }
  }
  return obj;
}
// 商城-订单-取消
function trackOrder(currentOrder, obj, event) {
  let tsActivityLimitList = !!currentOrder && !!currentOrder.addition.tsActivityLimitList ?
    currentOrder.addition.tsActivityLimitList?.[0] :
    !!currentOrder.addition.forwardPurchaseActivityList ?
    currentOrder.addition.forwardPurchaseActivityList?.[0] :
    "";
  let clTrackPrams = {
    c_product_id: "",
    c_product_name: "",
    c_product_brand: "",
    c_product_price: "",
    c_product_year: "",
    c_product_series: "",
    c_product_scenarios: "",
    c_product_taste: "",
    c_product_alcoholconcentration: "",
    c_product_volume: "",
    c_order_id: currentOrder.orderCode,
    c_quantity: currentOrder.itemQty,
    c_order_remark: currentOrder.buyerRemark,
    c_amount: currentOrder.payment,
    c_order_type: obj.orderType,
    c_purchase_type: obj.purchaseType,
    c_campaignID:
      !!tsActivityLimitList && !!tsActivityLimitList.tsActivityId ?
      tsActivityLimitList.tsActivityId :
      !!tsActivityLimitList.forwardPurchaseActivityId ?
      tsActivityLimitList.forwardPurchaseActivityId : "",
    c_campaignName:
      !!tsActivityLimitList && !!tsActivityLimitList.tsActivityName ?
      tsActivityLimitList.tsActivityName :
      !!tsActivityLimitList.forwardPurchaseActivityName ?
      tsActivityLimitList.forwardPurchaseActivityName : "",
  };

  currentOrder.items.forEach(function(item, index) {
    clTrackPrams.c_product_id += item.itemId + ";";
    clTrackPrams.c_product_name += item.itemName + ";";
    clTrackPrams.c_product_price += item.price + ";";
    clTrackPrams.c_product_volume = item.skuProperties[0].valueName || '' + ";";
  });
  getApp().commonClTrack(event, clTrackPrams);
}

function getTsById(id) {
  return new Promise(async (reslove, reject) => {
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let merchantInfo = uni.getStorageSync("merchantInfo");
    let memberDetails = uni.getStorageSync("memberDetails");
    if (!memberDetails || !customerInfo || !merchantInfo) {
      await commonLoginNew();
      await getMemberDetailNew();
      customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      merchantInfo = uni.getStorageSync("merchantInfo");
      memberDetails = uni.getStorageSync("memberDetails");
    }
    const result = await api.getTsById({
        header: {
          jwt: customerInfo.jwt,
        },
        method: "GET",
        query: {
          store_id: merchantInfo.cloudMerchantStoreId,
          group_id: customerInfo.groupId,
          member_level_id: memberDetails.memberLevelId,
        },
      },
      id
    );
    // if (result.code == 1000) {
      reslove(result.data);
    // } else {
    //   reject(result.data);
    // }
  });
}

function getRootCateTopLevel() {
  return new Promise(async (resolve, reject) => {
    let that = this;
    let merchantInfo = uni.getStorageSync("merchantInfo");
    const json = await api.merchantNavigation({
      query: {
        parent_nav_id: 0,
        store_id: merchantInfo.cloudMerchantStoreId,
      },
    });
    if (json.code === 1000) {
      // 一级列表
      let firstCategory = json.data.content;
      let rootcategory = [];
      let rootNavigation = [];
      if (firstCategory.length > 0) {
        for (let i in firstCategory) {
          if (
            firstCategory[i].visible > 0 &&
            firstCategory[i].foreignId !== 7956 &&
            firstCategory[i].foreignId !== 14366
          ) {
            rootcategory.push(firstCategory[i]);
          }
        }
      }

      if (rootcategory.length > 0) {
        for (var i = 0; i < rootcategory.length; i++) {
          firstCategory.push(rootcategory[i].navId);
          if (rootcategory[i]["parameters"]) {
            rootcategory[i].parameters = JSON.parse(
              rootcategory[i]["parameters"]
            );
          } else {
            rootcategory[i].parameters = {};
          }

          if (
            rootcategory[i].parameters["categoryGroup"] !== null &&
            rootcategory[i].parameters["categoryGroup"] !== undefined &&
            rootcategory[i].parameters["categoryGroup"] > 0
          ) {
            rootNavigation.push(rootcategory[i]);
          } else {
            rootcategory[i].parameters["categoryGroup"] = "0";
            rootNavigation.push(rootcategory[i]);
          }
        }

        rootNavigation.sort(function(a, b) {
          return a.parameters.categoryGroup - b.parameters.categoryGroup;
        });

        if (rootNavigation.length > 0) {
          for (let j = 0; j < rootNavigation.length - 1; j++) {
            if (
              rootNavigation[j].parameters["categoryGroup"] !=
              rootNavigation[j + 1].parameters["categoryGroup"]
            ) {
              rootNavigation[j].select = true;
            }
          }
        }
        // this.rootcateList = rootNavigation;
        resolve(rootNavigation);
      }
    } else {
      tip.plainText(json.msg);
      reject();
    }
  });
}

function getCmsInfo(identifier, isPreview) {
  return new Promise(async (resolve, reject) => {
    let that = this;
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    let mt = "1.0";
    const json = await api.getConfigDetail({
      method: "POST",
      query: {
        identifier: identifier,
        merchantId: merchantInfo.cloudMerchantId,
        storeId: merchantInfo.cloudMerchantStoreId,
        mt: mt,
      },
    });
    if (json.data.code === 1000 && json.data.data !== null) {
      let configData = json.data.data;
      let cmsConfigData = {};
      if (isPreview) {
        cmsConfigData = JSON.parse(configData.preview);
      } else {
        cmsConfigData = JSON.parse(configData.content);
        let contents = configData.contents;
        for (let index in contents) {
          let startTime = contents[index].startTime;
          startTime = startTime.substring(0, 19);
          startTime = startTime.replace(/-/g, "/");
          let startTimeTimestamp = new Date(startTime).getTime();
          if (startTimeTimestamp <= new Date().getTime()) {
            cmsConfigData = JSON.parse(contents[index].content);
            break;
          }
        }
      }
      resolve(cmsConfigData[0][0].data);
    } else {
      reject();
    }
  });
}

function getTsByUser() {
  return new Promise(async (reslove, reject) => {
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let merchantInfo = uni.getStorageSync("merchantInfo");
    let memberDetails = uni.getStorageSync("memberDetails");
    if (!memberDetails || !customerInfo || !merchantInfo) {
      await commonLoginNew();
      await getMemberDetailNew();
      customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      merchantInfo = uni.getStorageSync("merchantInfo");
      memberDetails = uni.getStorageSync("memberDetails");
    }
    const result = await api.getTsByUser({
      header: {
        jwt: customerInfo.jwt,
      },
      method: "GET",
      query: {
        store_id: merchantInfo.cloudMerchantStoreId,
        group_id: customerInfo.groupId,
        member_level_id: memberDetails.memberLevelId,
      },
    });
    if (result.code == 1000) {
      reslove(result.data);
    } else {
      reject(result.data);
    }
  });
}

function compareVersion(v1, v2) {
  // methods是需要点击后需要执行的函数， info是点击需要传的参数
  v1 = v1.split(".");
  v2 = v2.split(".");
  const len = Math.max(v1.length, v2.length);

  while (v1.length < len) {
    v1.push("0");
  }
  while (v2.length < len) {
    v2.push("0");
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i]);
    const num2 = parseInt(v2[i]);

    if (num1 > num2) {
      return 1;
    } else if (num1 < num2) {
      return -1;
    }
  }

  return 0;
}

/**
 * 分类下商品信息处理，拉去实时库存
 */
function buildClassifiedProducts(utoolsData) {
  return new Promise((resolve, reject) => {

  })
}

/**
 * 商品加入购物车
 * @param {Number} item.price 商品 item.skus[0].price
 * @param {Number} item.valueId 商品 item.frontProperties[0].valueId
 * @param {Number} item.itemCode 商品 item.itemId
 * @param {String} item.itemName 商品名称  item.itemName
 * @param {Number} item.qty      加购数量
 * @param {String} item.skuCode  sku编码 item.skus[0].skuCode
 * @param {String} item.skuId    skuid item.skus[0].skuId
 */
async function buildProductsAddCart(item) {
  try {
    if (typeof item != 'object') return {
      success: false,
      msg: "入参必须为对象"
    };
    if (!item?.itemCode || !item?.itemName || !item?.qty || !item?.skuCode || !item?.skuId) return {
      success: false,
      msg: "参数缺失"
    };
    const merchantInfo = uni.getStorageSync('merchantInfo');
    const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    if (!customerInfo) {
      return {
        success: false,
        msg: "加入购物袋失败",
        data: "用户信息不存在"
      };
    } else if (!merchantInfo) {
      return {
        success: false,
        msg: "加入购物袋失败",
        data: "商户信息不存在"
      };
    }
    const member = await illegalPhoneCheck();
    if(!member) return { success: false, msg: "加入购物袋失败", data: "当前手机号非中国大陆地区" };
    // 购物车校验参数
    const _cartQuery = {
      customerId: customerInfo.customerId,
      merchantId: merchantInfo.cloudMerchantId,
      orderSource: 'wxapp',
      storeId: merchantInfo.cloudMerchantStoreId
    };
    let _cartKey = "";
    //  检查购物车是否存在
    const _checkRes = await api.checkCart({
      method: 'POST',
      header: {
        jwt: customerInfo.jwt
      },
      query: _cartQuery
    });
    if (_checkRes.code === 1000) {
      _cartKey = _checkRes.data;
      uni.setStorageSync(CART_KEY, _cartKey);
      //  用户是否能加购判断
      const _checkPr = await checkGoodsPromotion(item,customerInfo, merchantInfo);
      if(_checkPr && _checkPr.success){
        //  加入购物车
        return await buildUserAddCart(item, customerInfo, merchantInfo, _cartKey);
      }else{
        return _checkPr;
      }
    } else {
      const _initRes = await api.initCart({
        method: 'POST',
        header: {
          jwt: customerInfo.jwt
        },
        query: _cartQuery
      });
      if (_initRes.code == 1000) {
        _cartKey = _initRes?.data?.cartKey;
        uni.setStorageSync(CART_KEY, _cartKey);
        //  用户是否能加购判断
        const _checkPr = await checkGoodsPromotion(item,customerInfo, merchantInfo);
        if(_checkPr && _checkPr.success){
          //  加入购物车
          return await buildUserAddCart(item, customerInfo, merchantInfo, _cartKey);
        }else{
          return _checkPr;
        }
      } else {
        return {
          success: false,
          msg: "加入购物袋失败",
          data: _initRes
        };
      }
    }
  } catch (e) {
    return {
      success: false,
      msg: "加入购物袋失败",
      data: e
    };
  }
}

/**
 * 商品加入购物车接口调用
 * @param {Object} item 商品信息集合
 * @param {Object} customerInfo   用户信息
 * @param {Object} merchantInfo   商户信息
 * @param {Object} cartKey        购物车key
 */
async function buildUserAddCart(item, customerInfo, merchantInfo, cartKey) {
  try {
    const resData = await api.addCart({
        method: 'POST',
        header: {
          jwt: customerInfo.jwt
        },
        query: {
          ...item,
          storeId: merchantInfo.cloudMerchantStoreId,
        }
      },
      cartKey + '/item'
    );
    if (resData.code == 1000) {
      return {
        success: true,
        msg: "已加入购物袋"
      };
    } else {
      let _msg = resData.code == -1002 ? "已超出限购数量，详情请咨询顾问" : (resData?.msg || "加入购物袋失败")
      if (_msg == '商品超出限购数量') _msg = "已超出限购数量，详情请咨询顾问";
      return {
        success: false,
        msg: _msg,
        data: resData
      };
    }
  } catch (e) {
    return {
      success: false,
      msg: "加入购物袋失败",
      data: e
    };
  }
}
/**
 * 用户加购等级判断
 * @param {Object} item
 * @param {Object} customerInfo
 * @param {Object} merchantInfo
 */
async function checkGoodsPromotion(item){
  try{
	let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
	let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    let memberDetails = uni.getStorageSync('memberDetails') || '';
    if (!memberDetails || !item.valueId) {
      return { success: false, msg: "当前等级不足，无法加购", data: null };
    }
    const json = await api.goodsPromotion({
        method: 'GET',
        query: {
          price: item.price
        }
      },
      merchantInfo.cloudMerchantId,
      merchantInfo.cloudMerchantStoreId,
      item.itemId,
      item.valueId
    );
    if (json.code === 1000) {
      let data = json.data;
      let tempPromotionArr = data;
      for (let t in tempPromotionArr) {
        const tagItem = tempPromotionArr[t];
        if (getApp().isDuringDate(tagItem.beginTime, tagItem.endTime)) {
          if (tagItem.promotionType == 'forward_purchase') {
            // 允许所有人购买
            if (!tagItem.groupIds && !tagItem.memberLevelIds) {
              return { success: true, msg: "可以加购", data: tagItem };
            } else if (!!tagItem.memberLevelIds && tagItem.memberLevelIds.indexOf(memberDetails.memberLevelId) !== -1 || (!!tagItem.groupIds && tagItem.groupIds.indexOf(customerInfo.groupId) !== -1)) {
              return { success: true, msg: "可以加购", data: tagItem };
            } else if (!!tagItem.memberLevelIds && tagItem.memberLevelIds.indexOf(memberDetails.memberLevelId) == -1) {
              return { success: false, msg: "当前等级不足，无法加购", data: tagItem };
            } else if (!!tagItem.groupIds && tagItem.groupIds.indexOf(customerInfo.groupId) == -1) {
              return { success: false, msg: "当前等级不足，无法加购", data: tagItem };
            }
          }
        }
      }
      return { success: true, msg: "可以加购", data: null };
    }
  }catch(e){
    return { success: false, msg: "当前等级不足，无法加购", data: null };
  }
}

/**
 * EB小程序utm报投放渠道信息 同步EF
 * 方案：
 * 首先需要EB小程序前端生成订单后，前端开发人员必须先调用utm保存接口，将EB前端计算后的渠道投放信息保存到cloud 数据库中，关联相应的订单。
 * 当订单支付成功或取消时，cloud后端收到订单支付成功或取消通知后，调用utm查询接口获取订单对应的utm信息，调用神策后端订单支付或取消相关事件时，上报utm信息。
 * @param {Object} customerInfo
 * @param {Object} merchantInfo
 * @param {String} orderCode    订单号
 */
async function handleSaveUtmByOrder(customerInfo, merchantInfo, orderCode) {
  try {
    const _pathQuery = getApp().globalData.pathOptions;
    // if(!_pathQuery|| !_pathQuery.utm_source || !_latestUtm) return false;
    if (!merchantInfo || !customerInfo || !merchantInfo.cloudMerchantId || !customerInfo.jwt || !merchantInfo
      .cloudMerchantStoreId) return false;
    const merchantId = merchantInfo.cloudMerchantId;
    const jwt = customerInfo.jwt;
    const storeId = merchantInfo.cloudMerchantStoreId;
    //  获取神策sdk预置属性
    const saData = commonSensors.getSdkPresetProperties();
    let latest_scene = "";
    if(saData && saData['$latest_scene']) latest_scene = saData['$latest_scene'];
    let _value = {
      "$latest_scene": latest_scene
    };
    //  utm
    if (_pathQuery && _pathQuery.utm_source) {
      _value = {
        ..._value,
        utm_campaign: _pathQuery.utm_campaign ? decodeURIComponent(_pathQuery.utm_campaign) : "",
        utm_source: _pathQuery.utm_source ? decodeURIComponent(_pathQuery.utm_source) : "",
        utm_medium: _pathQuery.utm_medium ? decodeURIComponent(_pathQuery.utm_medium) : "",
        utm_term: _pathQuery.utm_term ? decodeURIComponent(_pathQuery.utm_term) : "",
        utm_content: _pathQuery.utm_content ? decodeURIComponent(_pathQuery.utm_content) : "",
      }
    }
    //  first_utm
    const _firstUtm = uni.getStorageSync('firstUtmKey');
    if (_firstUtm && _firstUtm.first_utm_source) {
      _value = {
        ..._value,
        first_utm_campaign: _firstUtm.first_utm_campaign ? decodeURIComponent(_firstUtm.first_utm_campaign) : "",
        first_utm_source: _firstUtm.first_utm_source ? decodeURIComponent(_firstUtm.first_utm_source) : "",
        first_utm_medium: _firstUtm.first_utm_medium ? decodeURIComponent(_firstUtm.first_utm_medium) : "",
        first_utm_term: _firstUtm.first_utm_term ? decodeURIComponent(_firstUtm.first_utm_term) : "",
        first_utm_content: _firstUtm.first_utm_content ? decodeURIComponent(_firstUtm.first_utm_content) : "",
      }
    }
    //  latest_utm
    const _latestUtm = uni.getStorageSync('latestUtmKey');
    if (_latestUtm && _latestUtm.latest_utm_source) {
      _value = {
        ..._value,
        latest_utm_campaign: _latestUtm.latest_utm_campaign ? decodeURIComponent(_latestUtm.latest_utm_campaign) : "",
        latest_utm_source: _latestUtm.latest_utm_source ? decodeURIComponent(_latestUtm.latest_utm_source) : "",
        latest_utm_medium: _latestUtm.latest_utm_medium ? decodeURIComponent(_latestUtm.latest_utm_medium) : "",
        latest_utm_term: _latestUtm.latest_utm_term ? decodeURIComponent(_latestUtm.latest_utm_term) : "",
        latest_utm_content: _latestUtm.latest_utm_content ? decodeURIComponent(_latestUtm.latest_utm_content) : "",
      }
    }
    if (Object.keys(_value).length === 0) return console.log("#########  utm参数同步EF----utm为空 不同步");
    const key = `UTM:${merchantId}:${storeId}:${orderCode}`;
    const utmRes = await api.saveUtmInfoByOrder({
      method: 'POST',
      header: {
        jwt: jwt
      },
      query: {
        key: key,
        value: JSON.stringify(_value)
      }
    });
		if(commonMorefunLogs.aliYunMorefunLogs){
			//	莫凡日志
			commonMorefunLogs.aliYunMorefunLogs({
				msg: "下单UTM和$latest_scene参数存储",
				key: key,
				utmRes: utmRes.data ? JSON.stringify(utmRes.data) : JSON.stringify(utmRes)
			})
		}
    return utmRes;
  } catch (e) {
    return false;
  }
}

/**
 * 根据code 查询分享数据
 * @param {String} code
 */
async function getShareinfoByCode(code) {
  const { shareImage, shareTitle } = getApp().globalData;
  const pageRes = await getCurPagePath();
  let _shareImage = shareImage;
  let _shareTitle = shareTitle;
  try {
    if (code) {
      const shareRes = await api.getShareinfoByCode({
        code: code
      });
      if (shareRes && shareRes.success && shareRes.data && shareRes.data.value) {
        const res = JSON.parse(shareRes.data.value)
        _shareImage = res.imageUrl || _shareImage;
        _shareTitle = res.title || _shareTitle;
      }
    }
    return {
      pagePath: pageRes.path,
      pageQuery: pageRes.query,
      shareImage: _shareImage,
      shareTitle: _shareTitle
    };
  } catch (e) {
    return {
      pagePath: pageRes.path,
      pageQuery: pageRes.query,
      shareImage: _shareImage,
      shareTitle: _shareTitle
    };
  }
}
//  获取当前页面路径和参数
async function getCurPagePath() {
  let pages = getCurrentPages();
  let currPage = pages[pages.length - 1];
  const pageQuery = objectToUrlParams(currPage.options); //  获取url后面的参数
  return {
    path: currPage.route || "pages/home/home",
    query: pageQuery || ""
  }
}
//  对象转url参数
function objectToUrlParams(obj) {
  return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
}

// 抽签购商品暂存数组
let ballotGoodsLists = [];
/**
 * 组装处理utools中商品列表抽签购商品数据
 * @param {Object} utoolsJson   utools数据
 * @param {Object} goodsLists   商品分类列表数据
 */
async function buildBallotGoodsData(utoolsJson) {
  let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
  let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
  try {
    //  查询会员id
    let memberLevelId = await getMemberId(customerInfo);

    ballotGoodsLists = [];
    let _ballot = [];
    utoolsJson.children.forEach(item => {
      if (item.boxType == "draw" && item.type == "box") _ballot.push(item)
    });
    if (_ballot && _ballot.length) {
      for (let i = 0; i < _ballot.length; i++) {
        await filterUtoolsBallotGoods(_ballot[i])
      }
      //  查询订单
      const _orderLists = await getOrder(merchantInfo, customerInfo);
      //  抽签购商品存在，拉去数据
      if (ballotGoodsLists.length) {
        for (let k = 0; k < ballotGoodsLists.length; k++) {
          const _ele = ballotGoodsLists[k];
          _ele.isLuckyDrawItem = null;
          _ele.drawInfo = null;
          if(_ele.itemId){
            //  查询该用户是否参当前商品抽签购
            _ele.drawInfo = await getDrawInfo(customerInfo, merchantInfo, _ele.itemId, _ele.valueId, _ele.title_CH, memberLevelId, _orderLists);
          }
        }
      }
    }
    return ballotGoodsLists;
  } catch (e) {
    console.log("####  buildBallotGoodsData--error", e)
    return [];
  }
}



// 抽签购商品暂存数组
let searchBallotGoodsLists = [];
/**
 * 组装处理utools中商品列表抽签购商品数据
 * @param {Object} utoolsJson   utools数据
 * @param {Object} goodsLists   商品分类列表数据
 */
async function searchBuildBallotGoodsData(ballotGoodsLists=[]) {
  let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
  let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
  try {
    //  查询会员id
    let memberLevelId = await getMemberId(customerInfo);
      //  查询订单
      const _orderLists = await getOrder(merchantInfo, customerInfo);
      //  抽签购商品存在，拉去数据
      if (ballotGoodsLists.length) {
        for (let k = 0; k < ballotGoodsLists.length; k++) {
          const _ele = ballotGoodsLists[k];
          _ele.isLuckyDrawItem = null;
          _ele.drawInfo = null;
          if(_ele.itemId){
            //  查询该用户是否参当前商品抽签购
            _ele.drawInfo = await getDrawInfo(customerInfo, merchantInfo, _ele.itemId, _ele.valueId, _ele.title_CH, memberLevelId, _orderLists);
          }
        }
      }
    return ballotGoodsLists;
  } catch (e) {
    console.log("####  buildBallotGoodsData--error", e)
    return [];
  }
}


/**
 * 查询utools数据中商品列表模块是否包含抽签购
 * @param {Object} data  utools数据
 */
async function filterUtoolsBallotGoods(data) {
  try {
    if (data && data.type && data.type === 'commodityList' && data.commodityListType === "draw" && data.children
      .length) {
      ballotGoodsLists = ballotGoodsLists.concat(data.children);
      return true;
    }
    if (data && data.children && data.children.length) {
      for (let i = 0; i < data.children.length; i++) {
        if (data.children[i]) {
          filterUtoolsBallotGoods(data.children[i]);
        }
      }
    }
    return null;
  } catch (e) {}
}

/**
 * 判断当前商品是否参与抽签购
 * @param {Object} customerInfo
 * @param {Object} merchantInfo
 * @param {Object} goodsId  商品itemId
 * @param {Object} valueId  商品valueId
 * @param {Object} itemName  商品名称
 * @param {Object} memberLevelId  会员ID
 */
async function getDrawInfo(customerInfo, merchantInfo, itemId, valueId, itemName, memberLevelId, orderLists) {
  let json = await api.getDrawInfo({
    method: "GET",
    query: {
      store_id: merchantInfo.cloudMerchantStoreId,
      merchant_id: merchantInfo.cloudMerchantId,
      customer_id: customerInfo ? customerInfo.customerId : "",
      item_id: itemId,
      value_id: valueId,
    },
  });
  let backData = {};
  if (json && json.code === 1000 && json.data) {
    backData.order = null;
    const _data = json.data;
    //  本次活动仅限受邀用户参与
    let verifyDrawRes = await api.verifyDrawIdentify({
      method: 'POST',
      header: {
        jwt: customerInfo ? customerInfo.jwt : ''
      },
    }, _data.activitySelectionId);
    backData.activitySwitch = (json.code !== 1000) ? false : true;

    backData.ruleId = _data.activitySelectionDesc || 'drawRule'
    backData.activityInfo = _data;

    //  用户是否订阅当前商品的抽签购消息
    backData.remindSuccess = await isSecondRemindRquest(itemName, _data);

    let systemInfo = uni.getStorageSync(SYSTEM_INFO);
    let createTime = _data.createTime;
    let drawStartTime = _data.activitySelectionStartTime;
    let drawEndTime = _data.activitySelectionEndTime;
    let promulgateTime = _data.promulgateTime;
    let activityEndTime = _data.buyEndTime;
    let activityStopTime = _data.activityStopTime;
    backData.drawEndTime = formatDate(drawEndTime)
    let exCreateTime, exStartTime, exEndTime, expromulgateTime, buyEndTime;
    exCreateTime = createTime && util.formatTimeStamp(createTime);
    exStartTime = drawStartTime && util.formatTimeStamp(drawStartTime);
    expromulgateTime = promulgateTime && util.formatTimeStamp(promulgateTime);
    exEndTime = drawEndTime && util.formatTimeStamp(drawEndTime);
    buyEndTime = activityEndTime && util.formatTimeStamp(activityEndTime);
    activityStopTime = activityStopTime && util.formatTimeStamp(activityStopTime);
    backData.exTime = {
      exCreateTime,
      exStartTime,
      expromulgateTime,
      exEndTime,
      buyEndTime,
      activityStopTime
    }
    //  订单筛选
    let _order = orderLists.find(item=> {
      let ot = new Date(item.createTime).getTime();
      return item?.items[0]?.itemId == itemId && ot > exCreateTime;
    });
    backData.order = _order;
    backData.drawStartTrackTime = trackDate(exStartTime)
    backData.promulgateTrackTime = trackDate(expromulgateTime)
    backData.activityEndTrackTime = trackDate(buyEndTime)
    backData.exEndTrackTime = trackDate(exEndTime)
    backData.buyEndTrackTime = trackDate(buyEndTime)
    backData.memberLevelId = memberLevelId;
    backData.apiEnvironment = api.environment;
  } else {
    backData.activitySwitch = false;
  }
  return backData;
}

async function getOrder(merchantInfo,customerInfo){
  try{
    let that = this;
    const parmas = {
      customer_id: customerInfo.customerId,
      merchant_id: merchantInfo.cloudMerchantId,
      page_no: 1,
      page_size: 100,
      store_id: merchantInfo.cloudMerchantStoreId
    };
    let json = await api.getMyOrderList({
      header: {
        jwt: customerInfo.jwt
      },
      query: parmas
    });

    return json?.data?.data?.content || [];
  }catch(e){
    return [];
  }
}
//埋点北京时间转换成utc时间
function trackDate(timeStamp) {
  let timeDifference = timeStamp - 8 * 60 * 60 * 1000;
  let utcDateTime = util.timeFormat(timeDifference, true)
  return utcDateTime
}
//  时间格式化
function formatDate(date) {
  let data = date.slice(5, 10).replace('-', '月') + '日' + date.slice(11, 19)
  let month = data.substring(0, 2)
  if (month < 10) {
    data = data.slice(1)
  }
  return data
}

/**
 * 查询抽签购商品是否已订阅消息
 * @param {Object} itemName   商品名称
 * @param {Object} activityInfo  抽签购活动信息，接口api.getDrawInfo返回的内容
 */
async function isSecondRemindRquest(itemName, activityInfo) {
  try {
    let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
    const accountInfo = uni.getAccountInfoSync()
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
    if(!userSpecialInfo || !accountInfo) return false;
    let res = await api.getSaleMessage({
      method: 'POST',
      header: {
        jwt: customerInfo ? customerInfo.jwt : ''
      },
      query: {
        name: '甄选佳酿活动开始提醒',
        appId: accountInfo.miniProgram.appId,
        openId: userSpecialInfo.openid,
        params: {
          itemName: itemName,
          startTime: activityInfo.activitySelectionStartTime,
          activityId: activityInfo.activitySelectionId
        }
      }
    });
    if (res.code !== 1000) {
      return false
    } else {
      return true
    }
  } catch (e) {
    return false;
  }
}
//  会员等级查询
async function getMemberId(customerInfo) {
  try {
    let memberLevelId = 0;
    const memberLevelData = uni.getStorageSync('memberDetails');
    if(memberLevelData && memberLevelData.memberLevelId){
      memberLevelId = memberLevelData.memberLevelId;
    }else{
      //  查询用户会员信息
      if (!!customerInfo) {
        const memberDetailsResult = await api.getMemberDetails({
          header: {
            jwt: customerInfo.jwt
          }
        });
        if (memberDetailsResult.code == 1000 && memberDetailsResult.data) {
          const phoneNumberReg = /^1\d{10}$/;
          if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
            // 非大陆手机号按照非会员对待,重新入会
            uni.removeStorageSync('memberDetails');
          }else{
            uni.setStorageSync('memberDetails', memberDetailsResult.data)
            memberLevelId = memberDetailsResult.data.memberLevelId;
          }
        }
      }
    }
    return memberLevelId;
  } catch (e) {
    return 0;
  }
}

//  查询用户抽签购参与记录
async function getUserBalloutRecord(){
  try{
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    if(!customerInfo || !customerInfo.jwt) return [];
    let page_no = 1;
    let page_size = 100;
    const recordListResult = await getBalloutRecord(customerInfo.jwt, page_no, page_size);
    if (recordListResult.code == 1000 && recordListResult.data) {
      const _total = recordListResult.data.total;
      let _resLists = recordListResult.data.content || [];
      if(_total && _total > page_size){
        const _len = Math.ceil(_total[0].num/page_size);
        for (let i = 0; i < _len; i++) {
          page_no += 1;
          const recordResult = await getBalloutRecord(customerInfo.jwt, page_no, page_size);
          if(recordResult.code == 1000 && recordResult.data && recordListResult.data.content){
            _resLists = _resLists.concat(recordListResult.data.content);
          }
        }
      }
      return _resLists;
    }else{
      return [];
    }
  }catch(e){
    return [];
  }
}

/**
 * 查询用户抽签购记录
 * @param {Object} jwt
 * @param {Object} page_no
 * @param {Object} page_size
 */
async function getBalloutRecord(jwt, page_no, page_size){
  return await api.recordList({
    header: {
      jwt
    },
    query: {
      page_no,
      page_size,
    }
  });
}

module.exports = {
  preventDoubleClick: preventDoubleClick,
  getStoreConfigOnly: getStoreConfigOnly,
  getCurrentTime: getCurrentTime,
  moneyFormat: moneyFormat,
  priceRulesDeal: priceRulesDeal,
  commonShare: commonShare,
  unique: unique,
  isEnableEvaluate: isEnableEvaluate,
  getPdpEvaluate: getPdpEvaluate,
  getbasicAutoNumber: getbasicAutoNumber,
  reapplyJWT: reapplyJWT,
  commonUniLogin: commonUniLogin,
  commonLoginNew: commonLoginNew,
  checkCartNew: checkCartNew,
  getCartList: getCartList,
  getMemberDetailNew: getMemberDetailNew,
  doSearchGoods: doSearchGoods,
  getGoodsListFilter: getGoodsListFilter,
  setInitTaskCenter: setInitTaskCenter,
  getFourthLevelAddress: getFourthLevelAddress,
  preventReClick: preventReClick,
  getOrderInfo: getOrderInfo,
  getSqbToken: getSqbToken,
  sqbPay: sqbPay,
  payMoney: payMoney,
  timeStatus: timeStatus,
  getServerTime: getServerTime,
  getRootCateTopLevel: getRootCateTopLevel,
  getCmsInfo: getCmsInfo,
  trackOrder: trackOrder,
  getTsById: getTsById,
  getTsByUser: getTsByUser,
  isOrderType: isOrderType,
  compareVersion: compareVersion,
  getTabInfo: getTabInfo,
  buildProductsAddCart: buildProductsAddCart,
  handleSaveUtmByOrder: handleSaveUtmByOrder,
  getShareinfoByCode: getShareinfoByCode,
  buildBallotGoodsData: buildBallotGoodsData,
  getUserBalloutRecord: getUserBalloutRecord,
  searchBuildBallotGoodsData:searchBuildBallotGoodsData,
  checkGoodsPromotion:checkGoodsPromotion
};
